#ifndef __RenderSystem_H_
#define __RenderSystem_H_


#include "U2PreRequest.h"
#include "U2MemoryAllocatorConfig.h"
#include "U2RenderSystemCapabilities.h"
#include "U2Common.h"
#include "U2ConfigOptionMap.h"
#include "U2RenderTarget.h"
#include "U2RenderOperation.h"
#include "U2Matrix4.h"
#include "U2Plane.h"
#include "U2TextureUnitState.h"



U2EG_NAMESPACE_BEGIN


typedef std::map<U2String, U2RenderTarget*>      RenderTargetMap;
typedef std::multimap<u2uchar, U2RenderTarget*>  RenderTargetPriorityMap;
typedef std::vector<U2DepthBuffer*>              DepthBufferVec;
typedef std::map<u2uint16, DepthBufferVec>       DepthBufferMap;


enum TexCoordCalcMethod
{
    /// No calculated texture coordinates
    TEXCALC_NONE,
    /// Environment map based on vertex normals
    TEXCALC_ENVIRONMENT_MAP,
    /// Environment map based on vertex positions
    TEXCALC_ENVIRONMENT_MAP_PLANAR,
    TEXCALC_ENVIRONMENT_MAP_REFLECTION,
    TEXCALC_ENVIRONMENT_MAP_NORMAL,
    /// Projective texture
    TEXCALC_PROJECTIVE_TEXTURE
};


class U2RenderWindow;
class U2Viewport;
class U2DepthBuffer;
class U2TextureManager;


/** Defines the functionality of a 3D API
@remarks
    The RenderSystem class provides a base interface
    which abstracts the general functionality of the 3D API
    e.g. Direct3D or OpenGL. Whilst a few of the general
    methods have implementations, most of this class is
    abstract, requiring a subclass based on a specific API
    to be constructed to provide the full functionality.
    Note there are 2 levels to the interface - one which
    will be used often by the caller of the Ogre library,
    and one which is at a lower level and will be used by the
    other classes provided by Ogre. These lower level
    methods are prefixed with '_' to differentiate them.
    The advanced user of the library may use these lower
    level methods to access the 3D API at a more fundamental
    level (dealing direct with render states and rendering
    primitives), but still benefiting from Ogre's abstraction
    of exactly which 3D API is in use.
@author
    Steven Streeting
@version
    1.0
*/
class _U2Share U2RenderSystem : public RenderSysAlloc
{
public:
	/** Default Constructor.
	*/
	U2RenderSystem();

	/** Destructor.
	*/
	virtual ~U2RenderSystem();

	/** Returns the name of the rendering system.
	*/
	virtual const U2String& getName(void) const = 0;

	/** Returns the details of this API's configuration options.
	@remarks
	    Each render system must be able to inform the world
	    of what options must/can be specified for it's
	    operation.
	@par
	    These are passed as strings for portability, but
	    grouped into a structure (_ConfigOption) which includes
	    both options and current value.
	@par
	    Note that the settings returned from this call are
	    affected by the options that have been set so far,
	    since some options are interdependent.
	@par
	    This routine is called automatically by the default
	    configuration dialogue produced by Root::showConfigDialog
	    or may be used by the caller for custom settings dialogs
	@returns
	    A 'map' of options, i.e. a list of options which is also
	    indexed by option name.
	*/
	virtual U2ConfigOptionMap& getConfigOptions(void) = 0;

	/** Sets an option for this API.
	@remarks
	    Used to confirm the settings (normally chosen by the user) in
	    order to make the renderer able to initialise with the settings as required.
	    This may be video mode, D3D driver, full screen / windowed etc.
	    Called automatically by the default configuration
	    dialog, and by the restoration of saved settings.
	    These settings are stored and only activated when
	    RenderSystem::initialise or RenderSystem::reinitialise
	    are called.
	@par
	    If using a custom configuration dialog, it is advised that the
	    caller calls RenderSystem::getConfigOptions
	    again, since some options can alter resulting from a selection.
	@param
	    name The name of the option to alter.
	@param
	    value The value to set the option to.
	*/
	virtual void setConfigOption(const U2String &name, const U2String &value) = 0;

	/** Validates the options set for the rendering system, returning a message if there are problems.
	@note
	    If the returned string is empty, there are no problems.
	*/
	virtual U2String validateConfigOptions(void) = 0;

	/** Shutdown the renderer and cleanup resources.
	*/
	virtual void shutdown(void);

	/** Gets the capabilities of the render system. */
	const U2RenderSystemCapabilities* getCapabilities(void) const { return mCurrentCapabilities; }

    /** Query the real capabilities of the GPU and driver in the RenderSystem*/
    virtual U2RenderSystemCapabilities* createRenderSystemCapabilities() const = 0;

	/** Defines whether or now fullscreen render windows wait for the vertical blank before flipping buffers.
	@remarks
	    By default, all rendering windows wait for a vertical blank (when the CRT beam turns off briefly to move
	    from the bottom right of the screen back to the top left) before flipping the screen buffers. This ensures
	    that the image you see on the screen is steady. However it restricts the frame rate to the refresh rate of
	    the monitor, and can slow the frame rate down. You can speed this up by not waiting for the blank, but
	    this has the downside of introducing 'tearing' artefacts where part of the previous frame is still displayed
	    as the buffers are switched. Speed vs quality, you choose.
	@note
	    Has NO effect on windowed mode render targets. Only affects fullscreen mode.
	@param
	    enabled If true, the system waits for vertical blanks - quality over speed. If false it doesn't - speed over quality.
	*/
	void setWaitForVerticalBlank(bool enabled);

	/** Returns true if the system is synchronising frames with the monitor vertical blank.
	*/
	bool getWaitForVerticalBlank(void) const;

	/** Returns the driver version.
	*/
	virtual const DriverVersion& getDriverVersion(void) const { return mDriverVersion; }

	/** Creates a new rendering window.
	@remarks
	    This method creates a new rendering window as specified
	    by the paramteters. The rendering system could be
	    responible for only a single window (e.g. in the case
	    of a game), or could be in charge of multiple ones (in the
	    case of a level editor). The option to create the window
	    as a child of another is therefore given.
	    This method will create an appropriate subclass of
	    RenderWindow depending on the API and platform implementation.
	@par
	    After creation, this window can be retrieved using getRenderTarget().
	@param
	    name The name of the window. Used in other methods
	    later like setRenderTarget and getRenderTarget.
	@param
	    width The width of the new window.
	@param
	    height The height of the new window.
	@param
	    fullScreen Specify true to make the window full screen
	    without borders, title bar or menu bar.
	@param
	    miscParams A NameValuePairList describing the other parameters for the new rendering window. 
	    Options are case sensitive. Unrecognised parameters will be ignored silently.
	    These values might be platform dependent, but these are present for all platforms unless
	    indicated otherwise:
	    <table>
	    <tr>
		    <td><b>Key</b></td>
		    <td><b>Type/Values</b></td>
		    <td><b>Default</b></td>
		    <td><b>Description</b></td>
		    <td><b>Notes</b></td>
	    </tr>
	    <tr>
		    <td>title</td>
		    <td>Any string</td>
		    <td>U2RenderTarget name</td>
		    <td>The title of the window that will appear in the title bar</td>
		    <td>&nbsp;</td>
	    </tr>
	    <tr>
		    <td>colourDepth</td>
		    <td>16, 32</td>
		    <td>Desktop depth</td>
		    <td>Colour depth of the resulting rendering window; only applies if fullScreen</td>
		    <td>Win32 Specific</td>
	    </tr>
	    <tr>
		    <td>left</td>
		    <td>Positive integers</td>
		    <td>Centred</td>
		    <td>Screen x coordinate from left</td>
		    <td>&nbsp;</td>
	    </tr>
	    <tr>
		    <td>top</td>
		    <td>Positive integers</td>
		    <td>Centred</td>
		    <td>Screen y coordinate from left</td>
		    <td>&nbsp;</td>
	    </tr>
	    <tr>
		    <td>depthBuffer</td>
		    <td>true, false</td>
		    <td>true</td>
		    <td>Use depth buffer</td>
		    <td>DirectX9 specific</td>
	    </tr>
	    <tr>
		    <td>externalWindowHandle</td>
		    <td>Win32: HWND as integer<br/>
		        GLX: poslong:posint:poslong (display*:screen:windowHandle) or poslong:posint:poslong:poslong (display*:screen:windowHandle:XVisualInfo*)<br/>
                OS X: WindowRef for Carbon or NSWindow for Cocoa address as an integer
                iOS: UIWindow address as an integer
            </td>
		    <td>0 (none)</td>
		    <td>External window handle, for embedding the OGRE render in an existing window</td>
		    <td>&nbsp;</td>
	    </tr>
	    <tr>
		    <td>externalGLControl</td>
		    <td>true, false</td>
		    <td>false</td>
		    <td>Let the external window control OpenGL i.e. don't select a pixel format for the window,
		    do not change v-sync and do not swap buffer. When set to true, the calling application
		    is responsible of OpenGL initialization and buffer swapping. It should also create an
		    OpenGL context for its own rendering, Ogre will create one for its use. Then the calling
		    application must also enable Ogre OpenGL context before calling any Ogre function and
		    restore its OpenGL context after these calls.</td>
		    <td>OpenGL specific</td>
	    </tr>
	    <tr>
		    <td>externalGLContext</td>
		    <td>Context as Unsigned Long</td>
		    <td>0 (create own context)</td>
		    <td>Use an externally created GL context</td>
		    <td>OpenGL Specific</td>
	    </tr>
	    <tr>
		    <td>parentWindowHandle</td>
		    <td>Win32: HWND as integer<br/>
		        GLX: poslong:posint:poslong (display*:screen:windowHandle) or poslong:posint:poslong:poslong (display*:screen:windowHandle:XVisualInfo*)</td>
		    <td>0 (none)</td>
		    <td>Parent window handle, for embedding the OGRE in a child of an external window</td>
		    <td>&nbsp;</td>
	    </tr>
	    <tr>
		    <td>macAPI</td>
		    <td>U2String: "cocoa" or "carbon"</td>
		    <td>"carbon"</td>
		    <td>Specifies the type of rendering window on the Mac Platform.</td>
            <td>Mac OS X Specific</td>
		    <td>&nbsp;</td>
	     </tr>
	     <tr>
		    <td>macAPICocoaUseNSView</td>
		    <td>bool "true" or "false"</td>
		    <td>"false"</td>
		    <td>On the Mac platform the most diffused method to embed OGRE in a custom application is to use Interface Builder
			    and add to the interface an instance of OgreView.
			    The pointer to this instance is then used as "externalWindowHandle".
			    However, there are cases where you are NOT using Interface Builder and you get the Cocoa NSView* of an existing interface.
			    For example, this is happens when you want to render into a Java/AWT interface.
			    In short, by setting this flag to "true" the Ogre::Root::createRenderWindow interprets the "externalWindowHandle" as a NSView*
			    instead of an OgreView*. See OgreOSXCocoaView.h/mm.
		    </td>
            <td>Mac OS X Specific</td>
		    <td>&nbsp;</td>
	     </tr>
         <tr>
             <td>contentScalingFactor</td>
             <td>Positive Float greater than 1.0</td>
             <td>The default content scaling factor of the screen</td>
             <td>Specifies the CAEAGLLayer content scaling factor.  Only supported on iOS 4 or greater.
                 This can be useful to limit the resolution of the OpenGL ES backing store.  For example, the iPhone 4's
                 native resolution is 960 x 640.  Windows are always 320 x 480, if you would like to limit the display
                 to 720 x 480, specify 1.5 as the scaling factor.
             </td>
             <td>iOS Specific</td>
             <td>&nbsp;</td>
	     </tr>
         <tr>
             <td>externalViewHandle</td>
             <td>UIView pointer as an integer</td>
             <td>0</td>
             <td>External view handle, for rendering OGRE render in an existing view</td>
             <td>iOS Specific</td>
             <td>&nbsp;</td>
         </tr>
         <tr>
             <td>externalViewControllerHandle</td>
             <td>UIViewController pointer as an integer</td>
             <td>0</td>
             <td>External view controller handle, for embedding OGRE in an existing view controller</td>
             <td>iOS Specific</td>
             <td>&nbsp;</td>
         </tr>
         <tr>
		    <td>FSAA</td>
		    <td>Positive integer (usually 0, 2, 4, 8, 16)</td>
		    <td>0</td>
		    <td>Full screen antialiasing factor</td>
		    <td>&nbsp;</td>
	    </tr>
	    <tr>
		    <td>FSAAHint</td>
		    <td>Depends on RenderSystem and hardware. Currently supports:<br/>
		    "Quality": on systems that have an option to prefer higher AA quality over speed, use it</td>
		    <td>Blank</td>
		    <td>Full screen antialiasing hint</td>
		    <td>&nbsp;</td>
	    </tr>
	    <tr>
		    <td>displayFrequency</td>
		    <td>Refresh rate in Hertz (e.g. 60, 75, 100)</td>
		    <td>Desktop vsync rate</td>
		    <td>Display frequency rate, for fullscreen mode</td>
		    <td>&nbsp;</td>
	    </tr>
	    <tr>
		    <td>vsync</td>
		    <td>true, false</td>
		    <td>false</td>
		    <td>Synchronize buffer swaps to monitor vsync, eliminating tearing at the expense of a fixed frame rate</td>
		    <td>&nbsp;</td>
	    </tr>
	    <tr>
		    <td>vsyncInterval</td>
		    <td>1, 2, 3, 4</td>
		    <td>1</td>
		    <td>If vsync is enabled, the minimum number of vertical blanks that should occur between renders. 
		    For example if vsync is enabled, the refresh rate is 60 and this is set to 2, then the
		    frame rate will be locked at 30.</td>
		    <td>&nbsp;</td>
	    </tr>
	    <tr>
		    <td>border</td>
		    <td>none, fixed, resize</td>
		    <td>resize</td>
		    <td>The type of window border (in windowed mode)</td>
		    <td>&nbsp;</td>
	    </tr>
	    <tr>
		    <td>outerDimensions</td>
		    <td>true, false</td>
		    <td>false</td>
		    <td>Whether the width/height is expressed as the size of the 
		    outer window, rather than the content area</td>
		    <td>&nbsp;</td>
	    </tr>
	    <tr>
		    <td>useNVPerfHUD</td>
		    <td>true, false</td>
		    <td>false</td>
		    <td>Enable the use of nVidia NVPerfHUD</td>
		    <td>&nbsp;</td>
	    </tr>
	    <tr>
		    <td>gamma</td>
		    <td>true, false</td>
		    <td>false</td>
		    <td>Enable hardware conversion from linear colour space to gamma
		    colour space on rendering to the window.</td>
		    <td>&nbsp;</td>
	    </tr>
	    <tr>
		    <td>enableDoubleClick</td>
		    <td>true, false</td>
		    <td>false</td>
		    <td>Enable the window to keep track and transmit double click messages.</td>
		    <td>Win32 Specific</td>
	    </tr>
	*/
	virtual U2RenderWindow* _createRenderWindow(const U2String &name, unsigned int width, unsigned int height, 
		bool fullScreen, const NameValuePairList *miscParams = 0) = 0;

	/** Sets the provided viewport as the active one for future
	    rendering operations. This viewport is aware of it's own
	    camera and render target. Must be implemented by subclass.
	@param target Pointer to the appropriate viewport.
	*/
	virtual void _setViewport(U2Viewport *vp) = 0;
	/** Get the current active viewport for rendering. */
	virtual U2Viewport* _getViewport(void);

	/** Destroys a render window */
	virtual void destroyRenderWindow(const U2String& name);
	/** Destroys a render texture */
	virtual void destroyRenderTexture(const U2String& name);
	/** Destroys a render target of any sort */
	virtual void destroyRenderTarget(const U2String& name);
	/** Attaches the passed render target to the render system.
	*/
	virtual void attachRenderTarget(U2RenderTarget &target);
	/** Returns a pointer to the render target with the passed name, or NULL if that
	render target cannot be found.
	*/
	virtual U2RenderTarget * getRenderTarget(const U2String &name);
	/** Detaches the render target with the passed name from the render system and
	returns a pointer to it.
	@note
	If the render target cannot be found, NULL is returned.
	*/
	virtual U2RenderTarget * detachRenderTarget(const U2String &name);

	/// Iterator over RenderTargets
	typedef MapIterator<RenderTargetMap> RenderTargetIterator;

	/** Returns a specialised MapIterator over all render targets attached to the RenderSystem. */
	virtual RenderTargetIterator getRenderTargetIterator(void) {
		return RenderTargetIterator( mRenderTargets.begin(), mRenderTargets.end() );
	}

    /** Utility method for initialising all render targets attached to this rendering system. */
    virtual void _initRenderTargets(void);
	/** Internal method for updating all render targets attached to this rendering system. */
	virtual void _updateAllRenderTargets(bool swapBuffers = true);
	/** Internal method for swapping all the buffers on all render targets,
	if _updateAllRenderTargets was called with a 'false' parameter. */
	virtual void _swapAllRenderTargetBuffers(bool waitForVsync = true);


	/** Defines a listener on the custom events that this render system 
	    can raise.
	@see RenderSystem::addListener
	*/
	class _U2Share Listener
	{
	public:
		Listener() {}
		virtual ~Listener() {}

		/** A rendersystem-specific event occurred.
		@param eventName The name of the event which has occurred
		@param parameters A list of parameters that may belong to this event,
		may be null if there are no parameters
		*/
		virtual void eventOccurred(const U2String& eventName, 
			const NameValuePairList* parameters = 0) = 0;
	};

	/** Adds a listener to the custom events that this render system can raise.
	@remarks
	    Some render systems have quite specific, internally generated events 
	    that the application may wish to be notified of. Many applications
	    don't have to worry about these events, and can just trust OGRE to 
	    handle them, but if you want to know, you can add a listener here.
	@par
	    Events are raised very generically by string name. Perhaps the most 
	    common example of a render system specific event is the loss and 
	    restoration of a device in DirectX; which OGRE deals with, but you 
	    may wish to know when it happens. 
	@see RenderSystem::getRenderSystemEvents
	*/
	virtual void addListener(Listener* l);
	/** Remove a listener to the custom events that this render system can raise.
	*/
	virtual void removeListener(Listener* l);

	/** Gets a list of the rendersystem specific events that this rendersystem
	can raise.
	@see RenderSystem::addListener
	*/
	virtual const U2StringVector& getRenderSystemEvents(void) const { return mEventNames; }

	/** Start up the renderer using the settings selected (Or the defaults if none have been selected).
	@remarks
	    Called by Root::setRenderSystem. Shouldn't really be called
	    directly, although  this can be done if the app wants to.
	@param autoCreateWindow
        If true, creates a render window
	    automatically, based on settings chosen so far. This saves
	    an extra call to _createRenderWindow
	    for the main render window.
	@par
	    If an application has more specific window requirements,
	    however (e.g. a level design app), it should specify false
	    for this parameter and do it manually.
	@returns
	    A pointer to the automatically created window, if requested, otherwise null.
	*/
	virtual U2RenderWindow* _initialise(bool autoCreateWindow, const U2String& windowTitle = "U2 Render Window");

	/** Force the render system to use the special capabilities. Can only be called
	    before the render system has been fully initializer (before createWindow is called) 
	@param
	    capabilities has to be a subset of the real capabilities and the caller is 
	    responsible for deallocating capabilities.
	*/
	virtual void useCustomRenderSystemCapabilities(U2RenderSystemCapabilities* capabilities);

	/** Retrieves an existing DepthBuffer or creates a new one suited for the given RenderTarget
		and sets it.
	@remarks
		RenderTarget's pool ID is respected. @see RenderTarget::setDepthBufferPool()
	*/
	virtual void setDepthBufferFor( U2RenderTarget *renderTarget );

	/** Removes all depth buffers. Should be called on device lost and shutdown
	@remarks
		Advanced users can call this directly with bCleanManualBuffers=false to
		remove all depth buffers created for RTTs; when they think the pool has
		grown too big or they've used lots of depth buffers they don't need anymore,
		freeing GPU RAM.
	*/
	void _cleanupDepthBuffers( bool bCleanManualBuffers = true );

	/** Creates a DepthBuffer that can be attached to the specified RenderTarget
	@remarks
		It doesn't attach anything, it just returns a pointer to a new DepthBuffer
		Caller is responsible for putting this buffer into the right pool, for
		attaching, and deleting it. Here's where API-specific magic happens.
		Don't call this directly unless you know what you're doing.
	*/
	virtual U2DepthBuffer* _createDepthBufferFor( U2RenderTarget *renderTarget ) = 0;

	/** Render something to the active viewport.

	Low-level rendering interface to perform rendering
	operations. Unlikely to be used directly by client
	applications, since the SceneManager and various support
	classes will be responsible for calling this method.
	Can only be called between _beginScene and _endScene

	@param op A rendering operation instance, which contains
	details of the operation to be performed.
	*/
	virtual void _render(const U2RenderOperation& op);

	/**
	* Signifies the beginning of a frame, i.e. the start of rendering on a single viewport. Will occur
	* several times per complete frame if multiple viewports exist.
	*/
	virtual void _beginFrame(void) = 0;
	
	//Dummy structure for render system contexts - implementing RenderSystems can extend
	//as needed
	struct RenderSystemContext { };
	/**
	* Pause rendering for a frame. This has to be called after _beginFrame and before _endFrame.
	* Will usually be called by the SceneManager, don't use this manually unless you know what
	* you are doing.
	*/
	virtual RenderSystemContext* _pauseFrame(void);
	/**
	* Resume rendering for a frame. This has to be called after a _pauseFrame call
	* Will usually be called by the SceneManager, don't use this manually unless you know what
	* you are doing.
	* @param context the render system context, as returned by _pauseFrame
	*/
	virtual void _resumeFrame(RenderSystemContext* context);

	/**
	* Ends rendering of a frame to the current viewport.
	*/
	virtual void _endFrame(void) = 0;

	/** Clears one or more frame buffers on the active render target. 
	@param buffers Combination of one or more elements of FrameBufferType
	denoting which buffers are to be cleared
	@param colour The colour to clear the colour buffer with, if enabled
	@param depth The value to initialise the depth buffer with, if enabled
	@param stencil The value to initialise the stencil buffer with, if enabled.
	*/
	virtual void clearFrameBuffer(unsigned int buffers, 
		const U2ColourValue& colour = U2ColourValue::Black, 
		u2real depth = 1.0f/*, unsigned short stencil = 0*/) = 0;

    /** Sets how to rasterise triangles, as points, wireframe or solid polys. */
    virtual void _setPolygonMode(PolygonMode level) = 0;

    /** Sets the world transform matrix. */
    virtual void _setWorldMatrix(const U2Matrix4 &m) = 0;
    /** Sets the view transform matrix */
    virtual void _setViewMatrix(const U2Matrix4 &m) = 0;
    /** Sets the projection transform matrix */
    virtual void _setProjectionMatrix(const U2Matrix4 &m) = 0;
	/** Converts a uniform projection matrix to suitable for this render system.
	@remarks
	    Because different APIs have different requirements (some incompatible) for the
	    projection matrix, this method allows each to implement their own correctly and pass
	    back a generic OGRE matrix for storage in the engine.
	*/
	virtual void _convertProjectionMatrix(const U2Matrix4& matrix,
		U2Matrix4& dest, bool forGpuProgram = false) = 0;
	/** Builds an orthographic projection matrix suitable for this render system.
	@remarks
	    Because different APIs have different requirements (some incompatible) for the
	    projection matrix, this method allows each to implement their own correctly and pass
	    back a generic OGRE matrix for storage in the engine.
	*/
	virtual void _makeOrthoMatrix(const Radian& fovy, u2real aspect, u2real nearPlane, u2real farPlane, 
		U2Matrix4& dest, bool forGpuProgram = false) = 0;
	/** Utility method to notify all render targets that a camera has been removed, 
	in case they were referring to it as their viewer. 
	*/
	virtual void _notifyCameraRemoved(const U2Camera* cam);

	/**
	Sets the texture to bind to a given texture unit.

	User processes would not normally call this direct unless rendering
	primitives themselves.

	@param unit The index of the texture unit to modify. Multitexturing 
	hardware can support multiple units (see 
	RenderSystemCapabilites::getNumTextureUnits)
	@param enabled Boolean to turn the unit on/off
	@param texPtr Pointer to the texture to use.
	*/
	virtual void _setTexture(size_t unit, bool enabled, const U2TexturePtr &texPtr) = 0;

	/**
	Sets the texture coordinate set to use for a texture unit.

	Meant for use internally - not generally used directly by apps - the Material and TextureUnitState
	classes let you manage textures far more easily.

	@param unit Texture unit as above
	@param index The index of the texture coordinate set to use.
	*/
	virtual void _setTextureCoordSet(size_t unit, size_t index) = 0;

	/** Utility function for setting all the properties of a texture unit at once.
	This method is also worth using over the individual texture unit settings because it
	only sets those settings which are different from the current settings for this
	unit, thus minimising render state changes.
	*/
	virtual void _setTextureUnitSettings(size_t texUnit, TextureUnitState& tl);

	/** Binds a texture to a vertex sampler.
	@remarks
	    Not all rendersystems support separate vertex samplers. For those that
	    do, you can set a texture for them, separate to the regular texture
	    samplers, using this method. For those that don't, you should use the
	    regular texture samplers which are shared between the vertex and
	    fragment units; calling this method will throw an exception.
	@see RenderSystemCapabilites::getVertexTextureUnitsShared
	*/
	virtual void _setVertexTexture(size_t unit, const U2TexturePtr& tex);

	/** Sets the filtering options for a given texture unit.
	@param unit The texture unit to set the filtering options for
	@param minFilter The filter used when a texture is reduced in size
	@param magFilter The filter used when a texture is magnified
	@param mipFilter The filter used between mipmap levels, FO_NONE disables mipmapping
	*/
	virtual void _setTextureUnitFiltering(size_t unit, FilterOptions minFilter,
		FilterOptions magFilter, FilterOptions mipFilter);

	/** Sets a single filter for a given texture unit.
	@param unit The texture unit to set the filtering options for
	@param ftype The filter type
	@param filter The filter to be used
	*/
	virtual void _setTextureUnitFiltering(size_t unit, FilterType ftype, FilterOptions filter) = 0;

    /** Sets the maximal anisotropy for the specified texture unit.*/
    /**********************@@@@@@@@@@@@@@@@@@@@@
    virtual void _setTextureLayerAnisotropy(size_t unit, unsigned int maxAnisotropy) = 0;
    */

	/** Sets the mipmap bias value for a given texture unit.
	@remarks
	    This allows you to adjust the mipmap calculation up or down for a
	    given texture unit. Negative values force a larger mipmap to be used, 
	    positive values force a smaller mipmap to be used. Units are in numbers
	    of levels, so +1 forces the mipmaps to one smaller level.
	@note Only does something if render system has capability RSC_MIPMAP_LOD_BIAS.
	*/
	virtual void _setTextureMipmapBias(size_t unit, float bias) = 0;

	/** Sets the texture blend modes from a TextureUnitState record.
	Meant for use internally only - apps should use the Material
	and TextureUnitState classes.
	@param unit Texture unit as above
	@param bm Details of the blending mode
	*/
	virtual void _setTextureBlendMode(size_t unit, const LayerBlendModeEx& bm) = 0;

    /** Sets the texture addressing mode for a texture unit.*/
    virtual void _setTextureAddressingMode(size_t unit, const TextureUnitState::UVWAddressingMode& uvw) = 0;

    /** Sets the texture border colour for a texture unit.*/
    virtual void _setTextureBorderColour(size_t unit, const U2ColourValue& colour) = 0;

	/**
	Sets a method for automatically calculating texture coordinates for a stage.
	Should not be used by apps - for use by Ogre only.
	@param unit Texture unit as above
	@param m Calculation method to use
	@param frustum Optional Frustum param, only used for projective effects
	*/
    /**********************@@@@@@@@@@@@@@@@@@@@@
	virtual void _setTextureCoordCalculation(size_t unit, TexCoordCalcMethod m, 
		const U2Frustum* frustum = 0) = 0;
    */

	/** Sets the texture coordinate transformation matrix for a texture unit.
	@param unit Texture unit to affect
	@param xform The 4x4 matrix
	*/
	virtual void _setTextureMatrix(size_t unit, const U2Matrix4& xform) = 0;

    /** Turns off a texture unit. */
    virtual void _disableTextureUnit(size_t texUnit);

    /** Disables all texture units from the given unit upwards */
    virtual void _disableTextureUnitsFrom(size_t texUnit);

protected:
    /// Internal method for firing a rendersystem event
    virtual void fireEvent(const U2String& name, const NameValuePairList* params = 0);
    /** Initialize the render system from the capabilities. */
    virtual void initialiseFromRenderSystemCapabilities(U2RenderSystemCapabilities* caps, U2RenderTarget* primary) = 0;
    /// Internal method used to set the underlying clip planes when needed
    virtual void setClipPlanesImpl(const U2PlaneList& clipPlanes) = 0;

protected:

	/// Used to store the capabilities of the graphics card
	U2RenderSystemCapabilities*     mRealCapabilities;
	U2RenderSystemCapabilities*     mCurrentCapabilities;
	bool                            mUseCustomCapabilities;

    bool                            mVSync;

    DriverVersion                   mDriverVersion;

    /// Active viewport (dest for future rendering operations)
    U2Viewport*                     mActiveViewport;

    /// The render targets.
    RenderTargetMap                 mRenderTargets;
    /// The render targets, ordered by priority.
    RenderTargetPriorityMap         mPrioritisedRenderTargets;
    /// The Active render target.
    U2RenderTarget*                 mActiveRenderTarget;

    /// List of names of events this rendersystem may raise
    U2StringVector                  mEventNames;

    typedef std::list<Listener*>    ListenerList;
    ListenerList                    mEventListeners;

    /** DepthBuffers to be attached to render targets */
    DepthBufferMap                  mDepthBufferPool;

    /** Texture manager
        A concrete class of this will be created and
        made available under the TextureManager singleton,
        managed by the RenderSystem.
    */
    U2TextureManager                *mTextureManager;

    size_t                          mBatchCount;
    size_t                          mFaceCount;
    size_t                          mVertexCount;

    /// Texture units from this upwards are disabled
    size_t                          mDisabledTexUnitsFrom;

    // Recording user clip planes
    U2PlaneList                     mClipPlanes;
    // Indicator that we need to re-set the clip planes on next render call
    bool                            mClipPlanesDirty;

    /// Saved manual colour blends
    U2ColourValue                   mManualBlendColours[U2_MAX_TEXTURE_LAYERS][2];
};


U2EG_NAMESPACE_END


#endif
